package util;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xalan.internal.xsltc.trax.DOM2SAX;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import play.libs.XPath;
import scala.xml.Node;
import scala.xml.parsing.NoBindingFactoryAdapter;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by Administrator on 2016/3/8.
 */
public class DataFormatUtil {

    public static String mapToXmlString(Map<String, String> map, String head) {
        String result = "<" + head + ">";
        result += mapToXmlString(map);
        result += "</" + head + ">";
        return result;
    }

    public static String mapToXmlString(Map<String, String> map) {
        String result = "";
        for (String key : map.keySet()) {
            result += "<" + key + ">";
            result += map.get(key);
            result += "</" + key + ">";
        }
        return result;
    }

    public static InputStream createInputStreamFromString(String str) throws UnsupportedEncodingException {
        return createInputStreamFromString(str, "UTF-8");
    }

    public static InputStream createInputStreamFromString(String str, String encoding) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(str.getBytes(encoding));
    }

    //数据流转成字节组
    public static byte[] fullyReadStreamToBytes(InputStream inputStream) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[8092];
        while (inputStream.available() > 0) {
            int size = inputStream.read(bytes);
            byteArrayOutputStream.write(bytes, 0, size);
        }
        bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        return bytes;
    }

    //输入流转成字符串
    public static String fullyReadStream(InputStream inputStream) throws IOException {
        byte[] bytes = fullyReadStreamToBytes(inputStream);
        if (bytes == null) {
            return null;
        }
        return new String(bytes, "UTF-8");
    }


    //w3c document转成node类型
    public static Node w3cDocumentToScalaNode(org.w3c.dom.Document doc) {
        DOM2SAX dom2sax = new DOM2SAX(doc);
        NoBindingFactoryAdapter adapter = new NoBindingFactoryAdapter();
        dom2sax.setContentHandler(adapter);
        try {
            dom2sax.parse();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return adapter.rootElem();
    }

    public static void scalaNodeToObject(Object obj, org.w3c.dom.Document dom) {
        List<Field> fields = Common.getFields(obj);
        for (Field field : fields) {
            //play框架内置函数
            String value = XPath.selectText("//" + field.getName(), dom);
            if (value != null && value != "") {
                //中文乱码
                try {
                    value = new String(value.getBytes("iso8859-1"), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Class type = field.getType();
                field.setAccessible(true);
                Common.setValueOfObjecProperty(obj, field, value);
            }
        }
    }

    //简单的一层，而且都是对象
    public static JSONObject xmlStrToJSONObjectSimple(String xml) throws DocumentException {
        JSONObject result = new JSONObject();
        SAXReader reader = new SAXReader();
        Document doc;
        doc = DocumentHelper.parseText(xml);
        Element root = doc.getRootElement();
        for (Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element el = (Element) i.next();
            result.put(el.getName(), el.getData());
        }
        return result;
    }

    //去除html样式
    public static String trimHtml(String content) {
        // <p>段落替换为换行
        content = content.replaceAll("<p .*?>", "\r\n");
        // <br><br/>替换为换行
        content = content.replaceAll("<br\\s*/?>", "\r\n");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", "");
        // 还原HTML  // content = HTMLDecoder.decode(content);
        return content;
    }
}
